﻿using LightingPlatform.TCP;
using LightingPlatform.Tools;
using LightingPlatform.ViewModel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace LightingPlatform.View.Level5
{
    public partial class LightingView : UserControl, IPageProvider, IExportData
    {
        private LightingModel _lightingVM;
        private Lighting _sourceLighting;

        public LightingView()
        {
            InitializeComponent();

            FacadeBtn.Click += FacadeBtn_Click;
            GradingBtn.Click += GradingBtn_Click;
            SizeBtn.Click += SizeBtn_Click;
            LiveBtn.Click += LiveBtn_Click;
            OKBtn.Click += OKBtn_Click;
            CancelBtn.Click += CancelBtn_Click;

            for (int i = 0; i < 7; i++)
            {
                LayoutRoot.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(120) });
            }

            for (int i = 0; i < 21; i++)
            {
                LayoutRoot.RowDefinitions.Add(new RowDefinition() { Height = new GridLength((i + 1) % 3 == 0 ? 40 : 23) });
            }

            LayoutRoot.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });


            LightingTableFactory factory = new LightingTableFactory();
            LightingTable[] tables = new LightingTable[]
            {
                factory.CreateLighting(),
                factory.CreatePhysical(),
                factory.CreateOptics(),
                factory.CreateElectric(),
                factory.CreateAdapterLighting(),
                factory.CreateProject(),
                factory.CreateBusiness()
            };

            for (int i = 0; i < tables.Length; i++)
            {
                AddTable(tables[i], i * 3);
            }

            Loading();
        }

        public async void ExportToExcel()
        {
            if (string.IsNullOrEmpty(LightingContext.Singleton.QueryParameter5))
                return;

            busy.IsBusy = true;
            busy.BusyContent = "正在导出数据，请稍等......";
            byte[] response = await TCPClient.Current.Call((int)CommandType.QueryLevel5ExportExcel, Encoding.UTF8.GetBytes(LightingContext.Singleton.QueryParameter5));
            busy.IsBusy = false;
            if (response == null || response.Length == 0 || response[0] == 0)
            {
                MessageHelper.ShowError("加载数据出错。");
                return;
            }

            string url = Encoding.UTF8.GetString(response, 0, response.Length);
            HtmlPage.Window.Navigate(new Uri(url));
        }

        public async void ExportToPdf()
        {
            if (string.IsNullOrEmpty(LightingContext.Singleton.QueryParameter5))
                return;

            busy.IsBusy = true;
            busy.BusyContent = "正在导出数据，请稍等......";
            byte[] response = await TCPClient.Current.Call((int)CommandType.QueryLevel5ExportPdf, Encoding.UTF8.GetBytes(LightingContext.Singleton.QueryParameter5));
            busy.IsBusy = false;
            if (response == null || response.Length == 0 || response[0] == 0)
            {
                MessageHelper.ShowError("加载数据出错。");
                return;
            }

            string url = Encoding.UTF8.GetString(response, 0, response.Length);
            HtmlPage.Window.Navigate(new Uri(url));
        }

        private void CancelBtn_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(LightingContext.Singleton.QueryParameter5))
            {
                _lightingVM = new LightingViewModel();
                this.DataContext = _lightingVM;
            }
            else
            {
                if (_sourceLighting != null)
                {
                    _lightingVM = ConvertForm(_sourceLighting);
                    this.DataContext = _lightingVM;

                    foreach (ComboBox cb in _comboBoxs)
                    {
                        ISourceProvider provider = cb.Tag as ISourceProvider;
                        cb.SelectedIndex = provider.GetValue(_lightingVM);
                    }
                }
            }

        }

        private async void OKBtn_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(LightingContext.Singleton.QueryParameter5))
            {
                Lighting lighting = ConvertTo(_lightingVM);
                byte[] response = await TCPClient.Current.Call((int)CommandType.AddLighting, lighting.ToByteArray());
                if (response != null && response.Length > 0 && response[0] == (byte)1)
                {
                    MessageHelper.ShowMessage("添加灯具成功。");
                    _lightingVM = new LightingViewModel();
                    this.DataContext = _lightingVM;
                }
                else
                {
                    MessageHelper.ShowError("添加灯具失败。");
                }
            }
            else
            {
                Lighting lighting = ConvertTo(_lightingVM);
                byte[] response = await TCPClient.Current.Call((int)CommandType.EditLighting, lighting.ToByteArray());
                if (response != null && response.Length > 0 && response[0] == (byte)1)
                {
                    MessageHelper.ShowMessage("修改灯具成功。");
                    _lightingVM = new LightingViewModel();
                    this.DataContext = _lightingVM;
                }
                else
                {
                    MessageHelper.ShowError("修改添加灯具失败。");
                }
            }
            
        }

        private byte[] OpenDialog()
        {
            byte[] stream = null;

            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Filter = "Image files (*.jpg, *.jpeg, *.bmp, *.png) | *.jpg; *.jpeg; *.bmp; *.png";
            bool? result = fileDialog.ShowDialog();
            if (result.HasValue && result.Value)
            {
                string ext = fileDialog.File.Name.Substring(fileDialog.File.Name.LastIndexOf('.') + 1).ToLower();
                if (ext.Equals("bmp"))
                {
                    stream = Utility.ConvertFromBMP(fileDialog.File.OpenRead());
                }
                else
                {
                    using (Stream fs = fileDialog.File.OpenRead())
                    {
                        stream = Utility.ReadFully(fs);
                    }
                }
            }
            return stream;
        }

        private void FacadeBtn_Click(object sender, RoutedEventArgs e)
        {
            byte[] bytes = OpenDialog();
            if (bytes != null && bytes.Length > 0)
                _lightingVM.Picture.UploadFacade = bytes;
        }

        private void GradingBtn_Click(object sender, RoutedEventArgs e)
        {
            byte[] bytes = OpenDialog();
            if (bytes != null && bytes.Length > 0)
                _lightingVM.Picture.UploadGrading = bytes;
        }

        private void SizeBtn_Click(object sender, RoutedEventArgs e)
        {
            byte[] bytes = OpenDialog();
            if (bytes != null && bytes.Length > 0)
                _lightingVM.Picture.UploadSize = bytes;
        }

        private void LiveBtn_Click(object sender, RoutedEventArgs e)
        {
            byte[] bytes = OpenDialog();
            if (bytes != null && bytes.Length > 0)
                _lightingVM.Picture.UploadLive = bytes;
        }

        private void AddTable(LightingTable table, int startRowIndex)
        {
            SolidColorBrush brush = new SolidColorBrush(table.Backgroud);

            Grid tableTitle = CreateTitleCell(table.Name, startRowIndex, 0);
            tableTitle.Background = brush;
            LayoutRoot.Children.Add(tableTitle);
            Grid.SetRow(tableTitle, startRowIndex);

            int startColumnIndex = 0;
            foreach (ColumnProperty column in table.Columns)
            {
                Grid columnTitle = CreateTitleCell(column.Name, startRowIndex + 1, startColumnIndex);
                columnTitle.Background = brush;
                LayoutRoot.Children.Add(columnTitle);
                Grid.SetRow(columnTitle, startRowIndex + 1);
                Grid.SetColumn(columnTitle, startColumnIndex);

                Grid bindingCell = null;
                if (column is SelectorColumn)
                {
                    bindingCell = CreateBindingSelector((SelectorColumn)column, startRowIndex + 2, startColumnIndex);
                }
                else
                {
                    bindingCell = CreateBindingCell(column.Path, startRowIndex + 2, startColumnIndex, column.Span);
                }
                bindingCell.Background = brush;
                LayoutRoot.Children.Add(bindingCell);
                Grid.SetRow(bindingCell, startRowIndex + 2);
                Grid.SetColumn(bindingCell, startColumnIndex);

                if (column.Span > 1)
                {
                    Grid.SetColumnSpan(columnTitle, column.Span);
                    Grid.SetColumnSpan(bindingCell, column.Span);
                }

                startColumnIndex++;
            }
        }

        private Grid CreateTitleCell(string text, int rowIndex, int columIndex)
        {
            Grid grid = new Grid();

            Border border = new Border();
            border.BorderBrush = new SolidColorBrush(Colors.White);

            if (rowIndex == 0)
            {
                if (columIndex > 0)
                {
                    border.BorderThickness = new Thickness(1, 0, 0, 0);
                }
                else
                {
                    border.BorderThickness = new Thickness(0);
                }
            }
            else
            {
                if (columIndex == 0)
                {
                    border.BorderThickness = new Thickness(0, 1, 0, 0);
                }
                else
                {
                    border.BorderThickness = new Thickness(1, 1, 0, 0);
                }
            }

            grid.Children.Add(border);

            TextBlock tb = new TextBlock();
            tb.Text = text;
            tb.FontSize = 13;
            tb.HorizontalAlignment = HorizontalAlignment.Center;
            tb.VerticalAlignment = VerticalAlignment.Center;

            grid.Children.Add(tb);
            return grid;
        }

        private Grid CreateBindingCell(string path, int rowIndex, int columIndex, int colSpan)
        {
            Grid grid = new Grid();
            Border border = new Border();
            border.BorderBrush = new SolidColorBrush(Colors.White);

            if (columIndex == 0)
            {
                border.BorderThickness = new Thickness(0, 1, 0, 0);
            }
            else
            {
                border.BorderThickness = new Thickness(1, 1, 0, 0);
            }

            grid.Children.Add(border);

            TextBox tb = new TextBox();
            tb.Width = 120 * colSpan;
            tb.Height = 40;
            tb.FontSize = 13;
            tb.TextAlignment = TextAlignment.Center;
            tb.TextWrapping = TextWrapping.Wrap;
            tb.Background = new SolidColorBrush(Colors.Transparent);
            tb.BorderThickness = new Thickness(0);
            tb.HorizontalAlignment = HorizontalAlignment.Center;
            tb.VerticalAlignment = VerticalAlignment.Center;
            tb.SetBinding(TextBox.TextProperty, new Binding(path) { Mode = BindingMode.TwoWay });

            grid.Children.Add(tb);
            return grid;
        }

        private List<ComboBox> _comboBoxs = new List<ComboBox>();

        private Grid CreateBindingSelector(SelectorColumn column, int rowIndex, int columIndex)
        {
            Grid grid = new Grid();
            Border border = new Border();
            border.BorderBrush = new SolidColorBrush(Colors.White);

            if (columIndex == 0)
            {
                border.BorderThickness = new Thickness(0, 1, 0, 0);
            }
            else
            {
                border.BorderThickness = new Thickness(1, 1, 0, 0);
            }

            grid.Children.Add(border);

            ComboBox cb = new ComboBox();
            cb.Width = 120 * column.Span;
            cb.Height = 23;
            cb.FontSize = 13;
            cb.Background = new SolidColorBrush(Colors.Transparent);
            cb.BorderThickness = new Thickness(0);
            cb.HorizontalAlignment = HorizontalAlignment.Center;
            cb.VerticalAlignment = VerticalAlignment.Top;
            cb.Tag = column.Provider;
            cb.ItemsSource = column.Provider.ItemSource;
            cb.DisplayMemberPath = "ItemName";
            cb.SelectionChanged += (sender, e) =>
            {
                ResItem resItem = cb.SelectedItem as ResItem;
                column.Provider.SetValue(_lightingVM, resItem.ItemID);
            };
            grid.Children.Add(cb);
            _comboBoxs.Add(cb);
            return grid;
        }

        private async void Loading()
        {
            if (string.IsNullOrEmpty(LightingContext.Singleton.QueryParameter5))
            {
                _lightingVM = new LightingViewModel();
                this.DataContext = _lightingVM;
            }
            else
            {
                byte[] response = await TCPClient.Current.Call((int)CommandType.QueryLevel5, Encoding.UTF8.GetBytes(LightingContext.Singleton.QueryParameter5));
                if (response == null || response.Length == 0 || response[0] == 0)
                {
                    MessageHelper.ShowError("加载数据出错。");
                    return;
                }
                _sourceLighting = Lighting.ParseFrom(response);
                _lightingVM = ConvertForm(_sourceLighting);
                this.DataContext = _lightingVM;

                foreach (ComboBox cb in _comboBoxs)
                {
                    ISourceProvider provider = cb.Tag as ISourceProvider;
                    cb.SelectedIndex = provider.GetValue(_lightingVM);
                }
            }
        }

        private Lighting ConvertTo(LightingViewModel vm)
        {
            Lighting.Builder builder = new Lighting.Builder();

            builder.SetId(vm.ID);
            if (!string.IsNullOrEmpty(vm.Series))
                builder.SetSeries(vm.Series);
            if (vm.Class > 0)
                builder.SetClass(vm.Class);
            if (!string.IsNullOrEmpty(vm.Version))
                builder.SetVersion(vm.Version);
            if (!string.IsNullOrEmpty(vm.Lable))
                builder.SetLable(vm.Lable);
            if (vm.Place > 0)
                builder.SetPlace(vm.Place);
            if (vm.Orgin > 0)
                builder.SetOrgin(vm.Orgin);

            Physical.Builder pb = new Physical.Builder();
            pb.SetId(vm.Physical.ID);
            if (!string.IsNullOrEmpty(vm.Physical.Material))
                pb.SetMaterial(vm.Physical.Material);
            if (!string.IsNullOrEmpty(vm.Physical.Color))
                pb.SetColor(vm.Physical.Color);
            if (!string.IsNullOrEmpty(vm.Physical.Size))
                pb.SetSize(vm.Physical.Size);
            if (!string.IsNullOrEmpty(vm.Physical.Defend))
                pb.SetDefend(vm.Physical.Defend);
            if (vm.Physical.Impact > 0)
                pb.SetImpact(vm.Physical.Impact);
            if (!string.IsNullOrEmpty(vm.Physical.Weight))
            {
                double weight;
                if (double.TryParse(vm.Physical.Weight, out weight))
                    pb.SetWeight(weight);
            }
            builder.SetPhysical(pb.Build());

            Optics.Builder ob = new Optics.Builder();
            ob.SetId(vm.Optics.ID);
            if (vm.Optics.Explain > 0)
                ob.SetExplain(vm.Optics.Explain);
            if (!string.IsNullOrEmpty(vm.Optics.Angle))
                ob.SetAngle(vm.Optics.Angle);
            if (!string.IsNullOrEmpty(vm.Optics.Efficiency))
            {
                double efficiency;
                if (double.TryParse(vm.Physical.Weight, out efficiency))
                    ob.SetEfficiency(efficiency);
            }
            builder.SetOptics(ob.Build());

            Electric.Builder eb = new Electric.Builder();
            eb.SetId(vm.Electric.ID);
            if (!string.IsNullOrEmpty(vm.Electric.Shock))
                eb.SetShock(vm.Electric.Shock);
            if (vm.Electric.Voltage > 0)
                eb.SetVoltage(vm.Electric.Voltage);
            if (!string.IsNullOrEmpty(vm.Electric.Type))
                eb.SetType(vm.Electric.Type);
            if (!string.IsNullOrEmpty(vm.Electric.ElectricPower))
            {
                uint power;
                if (uint.TryParse(vm.Electric.ElectricPower, out power))
                    eb.SetElectricPower(power);
            }
            if (!string.IsNullOrEmpty(vm.Electric.AllPower))
            {
                uint power;
                if (uint.TryParse(vm.Electric.AllPower, out power))
                    eb.SetAllPower(power);
            }
            if (vm.Electric.ControlType > 0)
                eb.SetControlType(vm.Electric.ControlType);
            builder.SetElectric(eb.Build());

            AdapterLighting.Builder ab = new AdapterLighting.Builder();
            ab.SetId(vm.AdapterLighting.ID);
            if (vm.AdapterLighting.Class > 0)
                ab.SetClass(vm.AdapterLighting.Class);
            if (!string.IsNullOrEmpty(vm.AdapterLighting.Version))
                ab.SetVersion(vm.AdapterLighting.Version);
            if (!string.IsNullOrEmpty(vm.AdapterLighting.Color))
                ab.SetColor(vm.AdapterLighting.Color);
            if (!string.IsNullOrEmpty(vm.AdapterLighting.Cri))
            {
                uint cri;
                if (uint.TryParse(vm.AdapterLighting.Cri, out cri))
                    ab.SetCri(cri);
            }
            if (!string.IsNullOrEmpty(vm.AdapterLighting.Output))
            {
                uint output;
                if (uint.TryParse(vm.AdapterLighting.Output, out output))
                    ab.SetOutput(output);
            }
            if (!string.IsNullOrEmpty(vm.AdapterLighting.Pins))
                ab.SetPins(vm.AdapterLighting.Pins);
            builder.SetAdapterLighting(ab.Build());

            Project.Builder pb1 = new Project.Builder();
            pb1.SetId(vm.Project.ID);
            if (!string.IsNullOrEmpty(vm.Project.Parts))
                pb1.SetParts(vm.Project.Parts);
            if (vm.Project.Setup > 0)
                pb1.SetSetup(vm.Project.Setup);
            if (!string.IsNullOrEmpty(vm.Project.Size))
                pb1.SetSize(vm.Project.Size);
            if (!string.IsNullOrEmpty(vm.Project.Report))
                pb1.SetReport(vm.Project.Report);
            if (!string.IsNullOrEmpty(vm.Project.Baikup))
                pb1.SetBaikup(vm.Project.Baikup);
            builder.SetProject(pb1.Build());

            Business.Builder bb = new Business.Builder();
            bb.SetId(vm.Business.ID);
            if (!string.IsNullOrEmpty(vm.Business.In))
            {
                double price;
                if (double.TryParse(vm.Business.In, out price))
                    bb.SetIn(price);
            }
            if (!string.IsNullOrEmpty(vm.Business.Market))
            {
                double price;
                if (double.TryParse(vm.Business.Market, out price))
                    bb.SetMarket(price);
            }
            if (!string.IsNullOrEmpty(vm.Business.Out))
            {
                double price;
                if (double.TryParse(vm.Business.Out, out price))
                    bb.SetOut(price);
            }
            if (!string.IsNullOrEmpty(vm.Business.Delievery))
                bb.SetDelievery(vm.Business.Delievery);
            builder.SetBusiness(bb.Build());

            Picture.Builder pb2 = new Picture.Builder();
            pb2.SetId(vm.Picture.ID);
            if (vm.Picture.UploadFacade != null && vm.Picture.UploadFacade.Length > 0)
                pb2.SetUploadFacade(Google.ProtocolBuffers.ByteString.CopyFrom(vm.Picture.UploadFacade));
            if (vm.Picture.UploadSize != null && vm.Picture.UploadSize.Length > 0)
                pb2.SetUploadSize(Google.ProtocolBuffers.ByteString.CopyFrom(vm.Picture.UploadSize));
            if (vm.Picture.UploadGrading != null && vm.Picture.UploadGrading.Length > 0)
                pb2.SetUploadGrading(Google.ProtocolBuffers.ByteString.CopyFrom(vm.Picture.UploadGrading));
            if (vm.Picture.UploadLive != null && vm.Picture.UploadLive.Length > 0)
                pb2.SetUploadLive(Google.ProtocolBuffers.ByteString.CopyFrom(vm.Picture.UploadLive));
            builder.SetPicture(pb2.Build());
            return builder.Build();
        }

        private LightingViewModel ConvertForm(Lighting lighting)
        {
            LightingViewModel vm = new LightingViewModel();
            vm.ID = lighting.Id;
            if (lighting.HasSeries)
                vm.Series = lighting.Series;
            if (lighting.HasClass)
                vm.Class = lighting.Class;
            if (lighting.HasVersion)
                vm.Version = lighting.Version;
            if (lighting.HasLable)
                vm.Lable = lighting.Lable;
            if (lighting.HasPlace)
                vm.Place = lighting.Place;
            if (lighting.HasOrgin)
                vm.Orgin = lighting.Orgin;

            vm.Physical = new PhysicalVM();
            vm.Physical.ID = lighting.Physical.Id;
            if (lighting.Physical.HasMaterial)
                vm.Physical.Material = lighting.Physical.Material;
            if (lighting.Physical.HasColor)
                vm.Physical.Color = lighting.Physical.Color;
            if (lighting.Physical.HasSize)
                vm.Physical.Size = lighting.Physical.Size;
            if (lighting.Physical.HasDefend)
                vm.Physical.Defend = lighting.Physical.Defend;
            if (lighting.Physical.HasImpact)
                vm.Physical.Impact = lighting.Physical.Impact;
            if (lighting.Physical.HasWeight)
                vm.Physical.Weight = lighting.Physical.Weight.ToString();

            vm.Optics = new OpticsVM();
            vm.Optics.ID = lighting.Optics.Id;
            if (lighting.Optics.HasExplain)
                vm.Optics.Explain = lighting.Optics.Explain;
            if (lighting.Optics.HasAngle)
                vm.Optics.Angle = lighting.Optics.Angle.ToString();
            if (lighting.Optics.HasEfficiency)
                vm.Optics.Efficiency = lighting.Optics.Efficiency.ToString();

            vm.Electric = new ElectricVM();
            vm.Electric.ID = lighting.Electric.Id;
            if (lighting.Electric.HasShock)
                vm.Electric.Shock = lighting.Electric.Shock;
            if (lighting.Electric.HasVoltage)
                vm.Electric.Voltage = lighting.Electric.Voltage;
            if (lighting.Electric.HasType)
                vm.Electric.Type = lighting.Electric.Type;
            if (lighting.Electric.HasElectricPower)
                vm.Electric.ElectricPower = lighting.Electric.ElectricPower.ToString();
            if (lighting.Electric.HasLightingPower)
                vm.Electric.LightingPower = lighting.Electric.LightingPower;
            if (lighting.Electric.HasAllPower)
                vm.Electric.AllPower = lighting.Electric.AllPower.ToString();
            if (lighting.Electric.HasControlType)
                vm.Electric.ControlType = lighting.Electric.ControlType;

            vm.AdapterLighting = new AdapterLightingVM();
            vm.AdapterLighting.ID = lighting.AdapterLighting.Id;
            if (lighting.AdapterLighting.HasClass)
                vm.AdapterLighting.Class = lighting.AdapterLighting.Class;
            if (lighting.AdapterLighting.HasVersion)
                vm.AdapterLighting.Version = lighting.AdapterLighting.Version;
            if (lighting.AdapterLighting.HasColor)
                vm.AdapterLighting.Color = lighting.AdapterLighting.Color;
            if (lighting.AdapterLighting.HasCri)
                vm.AdapterLighting.Cri = lighting.AdapterLighting.Cri.ToString();
            if (lighting.AdapterLighting.HasOutput)
                vm.AdapterLighting.Output = lighting.AdapterLighting.Output.ToString();
            if (lighting.AdapterLighting.HasPins)
                vm.AdapterLighting.Pins = lighting.AdapterLighting.Pins;

            vm.Project = new ProjectVM();
            vm.Project.ID = lighting.Project.Id;
            if (lighting.Project.HasParts)
                vm.Project.Parts = lighting.Project.Parts;
            if (lighting.Project.HasSetup)
                vm.Project.Setup = lighting.Project.Setup;
            if (lighting.Project.HasSize)
                vm.Project.Size = lighting.Project.Size;
            if (lighting.Project.HasReport)
                vm.Project.Report = lighting.Project.Report;
            if (lighting.Project.HasBaikup)
                vm.Project.Baikup = lighting.Project.Baikup;

            vm.Business = new BusinessVM();
            vm.Business.ID = lighting.Business.Id;
            if (lighting.Business.HasIn)
                vm.Business.In = lighting.Business.In.ToString();
            if (lighting.Business.HasMarket)
                vm.Business.Market = lighting.Business.Market.ToString();

            if (lighting.Business.HasOut)

                vm.Business.Out = lighting.Business.Out.ToString();

            if (lighting.Business.HasDelievery)

                vm.Business.Delievery = lighting.Business.Delievery;


            vm.Picture = new PictureVM();
            vm.Picture.ID = lighting.Picture.Id;
            if (lighting.Picture.HasFacade)
                vm.Picture.FacadeView = lighting.Picture.Facade;
            if (lighting.Picture.HasLive)
                vm.Picture.LiveView = lighting.Picture.Live;
            if (lighting.Picture.HasSize)
                vm.Picture.SizeView = lighting.Picture.Size;
            if (lighting.Picture.HasGrading1)
                vm.Picture.Grading1View = lighting.Picture.Grading1;

            return vm;
        }

        public PageLevel PageLevel
        {
            get { return PageLevel.Fifth; }
        }
    }

    public class ColumnProperty
    {
        public string Name { get; set; }
        public string Path { get; set; }

        private int _span = 1;

        public int Span
        {
            get { return _span; }
            set { _span = value; }
        }
    }

    public interface ISourceProvider
    {
        IEnumerable<ResItem> ItemSource { get; }
        void SetValue(LightingViewModel vm, uint value);
        int GetValue(LightingViewModel vm);
    }

    public class SelectorColumn : ColumnProperty
    {
        public ISourceProvider Provider { get; set; }
    }

    public class LightingTable
    {
        public string Name { get; set; }
        public ColumnProperty[] Columns { get; set; }
        public Color Backgroud { get; set; }
    }

    public class LightingTableFactory
    {
        public LightingTable CreateLighting()
        {
            return new LightingTable()
            {
                Name = "产品描述",
                Columns = new ColumnProperty[]
                {
                    new ColumnProperty { Name = "产品品牌", Path = "Lable" },
                    new ColumnProperty { Name = "产品系列", Path = "Series" },
                    new SelectorColumn { Name = "产品分类", Path = "Class", Provider = new ProductSourceProvider() },
                    new ColumnProperty { Name = "产品型号", Path = "Version" },
                    new SelectorColumn { Name = "产    地", Path = "Orgin" , Provider  = new OrginSourceProvider() },
                    new SelectorColumn { Name = "使用场所", Path = "Place", Provider = new AreaSourceProvider() },
                },
                Backgroud = Color.FromArgb(255, 242, 242, 242),
            };
        }

        public LightingTable CreatePhysical()
        {
            return new LightingTable()
            {
                Name = "物理参数",
                Columns = new ColumnProperty[]
                {
                    new ColumnProperty { Name = "材质说明", Path = "Physical.Material" },
                    new ColumnProperty { Name = "外观颜色", Path = "Physical.Color" },
                    new ColumnProperty { Name = "外形尺寸", Path = "Physical.Size" },
                    new ColumnProperty { Name = "防护等级", Path = "Physical.Defend" },
                    new SelectorColumn { Name = "防撞击等级", Path = "hysical.Impact", Provider = new ImpactSourceProvider() },
                    new ColumnProperty { Name = "产品重量", Path = "Physical.Weight" },
                },
                Backgroud = Color.FromArgb(255, 217, 217, 217),
            };
        }

        public LightingTable CreateOptics()
        {
            return new LightingTable()
            {
                Name = "光学参数",
                Columns = new ColumnProperty[]
                {
                    new SelectorColumn { Name = "配光说明", Path = "Optics.Explain", Provider = new ExplainSourceProvider() },
                    new ColumnProperty { Name = "光束角", Path = "Optics.Angle" },
                    new ColumnProperty { Name = "灯具效率", Path = "Optics.Efficiency" }
                },
                Backgroud = Color.FromArgb(255, 191, 191, 191)

            };
        }

        public LightingTable CreateElectric()
        {
            return new LightingTable()
            {
                Name = "电气参数",
                Columns = new ColumnProperty[]
                {
                    new ColumnProperty { Name = "防触电等级", Path = "Electric.Shock" },
                    new SelectorColumn { Name = "工作电压", Path = "Electric.Voltage", Provider = new VoltageSourceProvider() },
                    new ColumnProperty { Name = "电器类型", Path = "Electric.Type"},
                    new ColumnProperty { Name = "电器功耗", Path = "Electric.ElectricPower" },
                    new ColumnProperty { Name = "光源功率", Path = "Electric.LightingPower" },
                    new ColumnProperty { Name = "整灯功耗", Path = "Electric.AllPower" },
                    new SelectorColumn { Name = "控制方式", Path = "Electric.ControlType", Provider = new ControlTypeSourceProvider() }
                },
                Backgroud = Color.FromArgb(255, 166, 166, 166)
            };
        }

        public LightingTable CreateAdapterLighting()
        {
            return new LightingTable()
            {
                Name = "适配光源",
                Columns = new ColumnProperty[]
                {
                    new SelectorColumn { Name = "光源种类", Path = "AdapterLighting.Class", Provider = new AdapterClassSourceProvider() },
                    new ColumnProperty { Name = "光源型号", Path = "AdapterLighting.Version" },
                    new ColumnProperty { Name = "色温或颜色", Path = "AdapterLighting.Color" },
                    new ColumnProperty { Name = "显色性", Path = "AdapterLighting.Cri" },
                    new ColumnProperty { Name = "光输出", Path = "AdapterLighting.Output" },
                    new ColumnProperty { Name = "插脚形式", Path = "AdapterLighting.Pins" }
                },
                Backgroud = Color.FromArgb(255, 128, 128, 128)
            };
        }

        public LightingTable CreateProject()
        {
            return new LightingTable()
            {
                Name = "工程参数",
                Columns = new ColumnProperty[]
                {
                    new ColumnProperty { Name = "安装方式", Path = "Project.Setup" },
                    new ColumnProperty { Name = "安装尺寸", Path = "Project.Size" },
                    new ColumnProperty { Name = "认证及检测报告", Path = "Project.Report" },
                    new ColumnProperty { Name = "备    注", Path = "Project.Baikup" },
                    new ColumnProperty { Name = "可选配件", Path = "Project.Parts", Span = 3 }
                },
                Backgroud = Color.FromArgb(255, 109, 109, 109)

            };
        }

        public LightingTable CreateBusiness()
        {
            return new LightingTable()
            {
                Name = "商务参数",
                Columns = new ColumnProperty[]
                {
                    new ColumnProperty { Name = "参考进价", Path = "Business.In" },
                    new ColumnProperty { Name = "市场参考价", Path = "Business.Market" },
                    new ColumnProperty { Name = "参考售价", Path = "Business.Out" },
                    new ColumnProperty { Name = "参考货期", Path = "Business.Delievery" }
                },
                Backgroud = Color.FromArgb(255, 89, 89, 89)
            };
        }
    }
}
